﻿using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace OfficeMiddlewareCore
{
    ///<summary>
    ///DES 加密
    /// </summary>
    public class DESService
    {
        private readonly DESCryptoServiceProvider _desc;

        public DESService(string key)
        {
            _desc = new DESCryptoServiceProvider();
            _desc.Mode = CipherMode.ECB;
            _desc.Key = Encoding.UTF8.GetBytes(key);

        }

        #region DESEnCode DES加密
        public string DESEnCode(string pToEncrypt)
        {
            byte[] inputByteArray = Encoding.UTF8.GetBytes(pToEncrypt);
            using (var ms = new MemoryStream())
            {
                using (var cs = new CryptoStream(ms, _desc.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(inputByteArray, 0, inputByteArray.Length);
                }
                var result = new StringBuilder();
                foreach (byte b in ms.ToArray())
                {
                    result.AppendFormat("{0:X2}", b);
                }
                return result.ToString();
            }
        }
        #endregion

        #region DESDeCode DES解密
        public string DESDeCode(string pToDecrypt)
        {
            var inputByteArray = new byte[pToDecrypt.Length / 2];
            for (int x = 0; x < pToDecrypt.Length / 2; x++)
            {
                int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));
                inputByteArray[x] = (byte)i;
            }
            try
            {

                using (var ms = new MemoryStream())
                {
                    using (var cs = new CryptoStream(ms, _desc.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(inputByteArray, 0, inputByteArray.Length);
                    }
                    return System.Text.Encoding.UTF8.GetString(ms.ToArray());
                }
            }
            catch (Exception ex)
            {
                return string.Empty;
            }
        }
        #endregion
    }
}
